package model;

import java.util.LinkedList;
import java.util.ListIterator;

import javax.sound.midi.Receiver;

import library.Cue;
import library.State;

public class CueStack {
	private LinkedList<Cue> cuestack;
	private int current;
	
	public CueStack()
	{
		cuestack = new LinkedList<Cue>();
	}
	public int size()
	{
		return cuestack.size();
	}
	public void add(Cue cue)
	{
		cuestack.add(cue);
	}
	public Cue remove(int index)
	{
		Cue q = cuestack.remove(index);
		renumber(index);
		return q;
	}
	/**MUST CALL RENUMBER**/
	public void reassign(int old, int next)
	{
		Cue oldCue = cuestack.get(old);
		cuestack.remove(old);
		cuestack.add(next, oldCue);
		renumber(next);
	}
	public void select(int number)
	{
		for(int x = 0; x < cuestack.size(); x++)
			if(cuestack.get(x).getNum() == number)
				current = x;
	}
	public String displayNote()
	{
		return cuestack.get(current).getNote().toString();
	}
	public void setNote(StringBuilder note)
	{
		cuestack.get(current).setNote(note);
	}
	private void renumber(int start)
	{
		for(int x = start; x < cuestack.size(); x++)
			cuestack.get(x).setNum(x-1);
	}
	public Cue load()
	{
		Cue q = null;
		try{
			q = cuestack.get(current);
		} catch (IndexOutOfBoundsException e) {
			current = 0;
			load();
		}
		return q;
	}
	public void fire(Cue cue, Receiver fedex)
	{

		if(cue instanceof AudioQ)
		{
			((AudioQ)cue).play();
			current++;
		}
		else if(fedex == null)
			return;
		else if(cue instanceof ExpressQ)
		{
			fedex.send(((((ExpressQ) cue).getMessage())), -1);
			current++;
		}
	}
	private void reset()
	{
		current = 0;
	}
	public void stopAll()
	{
		for(Cue q : cuestack)
			if(q instanceof AudioQ)
				((AudioQ) q).stop();
		reset();
	}
	public State statement()
	{
		State state = new State();
		state.setState(cuestack.clone());
		return state;
	}
}
